package com.yt.db.config;

import com.yt.db.constant.DataSourceEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSource extends AbstractRoutingDataSource {

    private DataSource defaultDataSource; //默认数据源

    @Autowired
    private DataSource dataSourceWirte;
    @Autowired
    private DataSource dataSourceRead;


    @Override
    public void afterPropertiesSet() {
        defaultDataSource = dataSourceWirte;
        setDefaultTargetDataSource(defaultDataSource);

        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceEnum.dataSourceWirte.getCode() , dataSourceWirte);
        targetDataSources.put(DataSourceEnum.dataSourceRead.getCode() , dataSourceWirte);

        // 设置数据源
        setTargetDataSources(targetDataSources);
        //获取配置信息
        DataSourceContextHolder.setDataSource(DataSourceEnum.dataSourceWirte);
        super.afterPropertiesSet();
    }

    /**
     * 取得当前使用哪个数据源
     *
     * @return Object
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }
}
